package com.fast.filter;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.extension.api.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.bcel.classfile.Constant;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

/**
 * @author hjw
 * @since 2022年03月24日 11:24:00
 */
//@Component
@Slf4j
public class AuthFilter implements Filter, Ordered {

    private static final String AUTHORIZE_TOKEN = "token";

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        boolean isFilter = false;
        String token = req.getHeader(AUTHORIZE_TOKEN);//header方式

        String requestURL = req.getRequestURL().toString();
        if (requestURL.contains("/login") || requestURL.contains("/doc.html")) {
            chain.doFilter(request, response);
        }
        R<Object> resultInfo = new R<>();
        if (null == token || token.isEmpty()) {
            resultInfo.setCode(403);
            resultInfo.setMsg("用户授权认证没有通过!客户端请求参数中无token信息");
        } else {
            if (JWTUtil.verify(token, "ceshi".getBytes())) {
                resultInfo.setCode(200);
                resultInfo.setMsg("用户授权认证通过!");
                isFilter = true;
            } else {
                resultInfo.setCode(403);
                resultInfo.setMsg("用户授权认证没有通过!客户端请求参数token信息无效");
            }
        }
        if (resultInfo.getCode() == 403) {
            PrintWriter writer = null;
            OutputStreamWriter osw = null;
            try {
                osw = new OutputStreamWriter(response.getOutputStream(),
                        "UTF-8");
                writer = new PrintWriter(osw, true);
                String jsonStr = JSONUtil.toJsonStr(resultInfo);
                writer.write(jsonStr);
                writer.flush();
                writer.close();
                osw.close();
            } catch (UnsupportedEncodingException e) {
                log.error("过滤器返回信息失败:" + e.getMessage(), e);
            } catch (IOException e) {
                log.error("过滤器返回信息失败:" + e.getMessage(), e);
            } finally {
                if (null != writer) {
                    writer.close();
                }
                if (null != osw) {
                    osw.close();
                }
            }
        }

        if (isFilter) {
            log.info("token 校验通过!");
            chain.doFilter(request, response);
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
